<template>
  <div class="h100 tableSearchListFlexPage">
    <div class="tableSearchMain commonSelectWidth table-page-search-wrapper">
      <a-row :gutter="[16]">
        <a-col :md="3" :sm="24">
          <a-select
            v-model="queryParam.ecuName"
            allow-clear
            showSearch
            :filter-option="false"
            :placeholder="$t('pleaseSelect') + $t('lingjian')"
            style="width: 100%"
            @search="getEcuList"
            @change="refreshData"
            :notFoundContent="isSearch ? $t('noData') : $t('ecuNameSearch')"
          >
            <a-select-option
              v-for="item in ecuList"
              :key="item.ecuModuleId"
              :value="`${item.ecuName}/${item.ecuModuleId}`"
              :title="`${item.ecuName}/${item.ecuModuleId}`"
            >
              {{ `${item.ecuName}/${item.ecuModuleId}` }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-input
            v-model.trim="queryParam.softwareVersion"
            :placeholder="$t('pleaseInput') + $t('versionName').toLowerCase()"
            @keyup.enter="refreshData"
            allowClear
          />
        </a-col>
        <a-col :md="4" :sm="24">
          <a-select
            v-model="queryParam.softwareStatus"
            allow-clear
            :placeholder="$t('pleaseSelect') + '软件包状态'"
            style="width: 100%"
            @change="refreshData(true)"
          >
            <a-select-option
              v-for="(item, index) in softwareMakeStatusDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :md="4" :sm="24">
          <a-select
            v-model="queryParam.softwareType"
            allow-clear
            :placeholder="$t('pleaseSelect') + '软件包类型'"
            style="width: 100%"
            @change="refreshData(true)"
          >
            <a-select-option
              v-for="(item, index) in softwareMakeTypeDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :md="10" :sm="24">
          <div class="searchBtns">
            <a-button-group>
              <auth-button @click="refreshData" type="primary">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="clear">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button @click="showSwEncrypt" type="primary">
              软件包加密
            </auth-button>
            <auth-button @click="showOnlineDifference" type="primary">
              {{ $t('onlineDifference') }}
            </auth-button>
            <question-mark-tip :tip-title="onlineDifferenceTip" >
            </question-mark-tip>
          </div>
        </a-col>
      </a-row>
    </div>
    <div class="tableListMain withMinHeightTbodyBox">
      <s-table
        ref="table"
        class="h100"
        :rowKey="(record, index) => record.id"
        :columns="columns"
        :data="loadData"
        :scrollX="900"
      >
        <template #softwareVersion="text,record">
          <span v-if="record.softwareType === 'diff'">{{record.sourceSoftwareVersion}}<span class="arrow"> → </span></span>{{record.targetSoftwareVersion}}
        </template>
        <template #softwareStatus="text,record">
          <div>{{$store.getters.getDictCodeObj('softwareMakeStatusDictCode')[text] || text}}
            <question-mark-tip :tip-title="record.failedReason" v-if="text === 'failed'">
            </question-mark-tip></div>
        </template>
        <template #process="text,record">
          <div style="position: relative">
            <a @click="showProcess(record)">
              <a-progress :percent="text/40*100" :show-info="false" style="width: 70%; color: blue; cursor:pointer"/>
            </a>
          <span style="width: 30%;margin-left:5px">{{text/40*100}}%</span>
          </div>
        </template>
        <template slot="operationTime" slot-scope="text">
          <table-ellipsis
            :tableEllipsisIsTurnLine="false"
            :text="text ? $options.filters.moment(text) : '-'">
          </table-ellipsis>
        </template>
        <template #action="text,record">
          <span class="tableOperateSty" style="display: flex;">
            <auth-button v-if="record.softwareStatus == 'succeed'" :ghost="true" size="small" @click="download(record)" :loading="record.downloading">
              {{ $t('download') }}
            </auth-button>
            <auth-button v-if="record.softwareStatus == 'failed'" :ghost="true" size="small" @click="retry(record)" :loading="record.retrying">
              重试
            </auth-button>
            <auth-button v-if="record.softwareStatus == 'succeed'" :ghost="true" size="small" @click="repeal(record)" :loading="record.repealing">
              废弃
            </auth-button>
          </span>
        </template>
      </s-table>
    </div>
    <!-- 升级进度弹框 -->
    <process-file ref="processRef" :processId="processId"></process-file>
  </div>
</template>
<script>
import { swPackageProdCols } from '@/views/software/swPackageProd/config/list'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import {minxinDrawerUse} from "@/utils/mixin";
import SwEncryptCompt from './components/swEncryptCompt.vue'
import OnlineDiffCompt from './components/onlineDiffCompt.vue'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import lodash from 'lodash'
import { mapState } from 'vuex'
import {downloadBlobFile} from "@/utils/functions";
import ProcessFile from '../partsSoftware/components/ProcessFile.vue';

export default {
  name: 'swPackageProd',
  components: {
    QuestionMarkTip,
    SwEncryptCompt,
    TableEllipsis,
    ProcessFile
  },
  mixins: [minxinDrawerUse],
  data () {
    return {
      ecuList: [], // ecu列表
      queryParam: {
        ecuName:undefined
      },
      isSearch: false,
      columns: swPackageProdCols,
      onlineDifferenceTip:'当前在线差分工具仅支持明文包加密，加密后差分包请使用软件管控中差分工具！',
      processId:''
    }
  },
  mounted(){
    this.$store.dispatch('getSoftwareMakeStatusDictCodeData')
    this.$store.dispatch('getSoftwareMakeTypeDictCodeData')
  },
  computed:{
    ...mapState({
      softwareMakeStatusDictCode: (state) => state.dict.softwareMakeStatusDictCode,
      softwareMakeTypeDictCode: (state) => state.dict.softwareMakeTypeDictCode,
    }),
  },
  methods: {
    download(record){
      this.$set(record, 'downloading', true)
      this.$api.softwareDownload(record.resourceId).then((res) => {
        downloadBlobFile(res, record.resourceName)
      }).finally(()=>{
        this.$set(record, 'downloading', false)
      })
    },
    retry(record){
      this.$set(record, 'retrying', true)
      this.$api.softwareRetry({id:record.id}).then(res=>{
        this.refreshData()
      }).finally(()=>{
        this.$set(record, 'retrying', false)
      })
    },
    repeal(record){
      this.$set(record, 'repealing', true)
      this.$api.softwareDisabled({id:record.id}).then(res=>{
        this.refreshData()
      }).finally(()=>{
        this.$set(record, 'repealing', false)
      })
    },
    showProcess (record) {
      this.processId = record.resourceId.toString()
      this.$refs.processRef.visible = true
    },
    loadData(page) {
      this.queryParam.ecuName = this.queryParam.ecuName && this.queryParam.ecuName.split('/')[0]
      return this.$api.getSoftwareMakeList({...this.queryParam, ...page});
    },
    clear() {
      this.queryParam = {};
      this.refreshData(true);
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.table.refresh(isToFirstPage)
      })
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = {}
      this.refreshData()
    },
    getEcuList:lodash.debounce(function(value = '') {
      const vm = this
      vm.ecuList = []
      vm.isSearch = false
      if (value) {
        vm.$api
          .getSoftwareMakeEcuList({ ecuName: value.trim() ,pageSize:1000 })
          .then((res) => {
            if(res.data.length>0){
              vm.ecuList = res.data
            }else{
              vm.isSearch = true
            }
          })
      }
    },500),
    saveSwEncrypt(data){
      return new Promise((resolve, reject) => {
        this.$api.softwareMakeEncrypt(data).then(res => {
          resolve(res)
          this.refreshData(true)
        }).catch(err => {
          reject(err)
        })
      })
    },
    saveOnlineDiff(data){
      return new Promise((resolve, reject) => {
        this.$api.softwareMakeDiff(data).then(res => {
          resolve(res)
          this.refreshData(true)
        }).catch(err => {
          reject(err)
        })
      })
    },
    showSwEncrypt(){
      const buttons = this.getRightDrawerFooterButtons({
        method: 'saveSwEncrypt',
      })
      this.showRightDrawerNoReset(SwEncryptCompt, this.$t('软件包加密'), buttons, 'small', {});
    },
    showOnlineDifference(){
      const buttons = this.getRightDrawerFooterButtons({
        method: 'saveOnlineDiff',
      })
      this.showRightDrawerNoReset(OnlineDiffCompt, this.$t('onlineDifference'), buttons, 'small', {});
    },
  }
}
</script>
<style lang="less" scoped>
.arrow{
  color:deepskyblue
}
</style>
